﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Configuration;

namespace Interfleet.SE.UICompiler.Core.ClosureCompiler
{
    /// <summary>
    /// This class builds up the command line arguments for the local Google Closure Compiler
    /// application.
    /// </summary>
    public class CCArgumentBuilder : ArgumentBuilder
    {
        #region Constructor

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="arguments"><see cref="Arguments"/> for the compilation</param>
        public CCArgumentBuilder(Arguments arguments)
            : this(arguments, new FileProvider())
        { }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="arguments"><see cref="Arguments"/> for the compilation</param>
        /// <param name="fileInfoProvider">An instance of <see cref="IFileProvider"/></param>
        public CCArgumentBuilder(Arguments arguments, IFileProvider fileInfoProvider)
            : base(arguments, fileInfoProvider, new CCCompileOptions())
        {

        }
        #endregion

        protected override string AppFolder
        {
            get
            {
                var path = base.AppFolder;
                var defaultPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "UI Compiler .NET");
                if (Directory.Exists(defaultPath))
                {
                    path = defaultPath;
                }
                return path;
            }
        }

        /// <summary>
        /// Builds up a string of command line arguments to the Closure Compiler Java component
        /// </summary>
        /// <returns></returns>
        public override string Build()
        {
            string compilerPath = Path.Combine(AppFolder, @"Components\compiler.jar");
            // config settings overrides...
            if (ConfigurationManager.AppSettings.AllKeys.Contains("UICompiler.ClosureCompilerPath")
                && File.Exists(ConfigurationManager.AppSettings["UICompiler.ClosureCompilerPath"]))
            {
                compilerPath = ConfigurationManager.AppSettings["UICompiler.ClosureCompilerPath"];
            }
            var sb = new StringBuilder();
            sb.AppendFormat("-jar \"{0}\" --charset UTF-8", compilerPath);
            foreach (var file in Arguments.Files)
            {
                sb.AppendFormat(" --js \"{0}\"", file);
            }
            sb.AppendFormat(" --js_output_file \"{0}\"", Arguments.CompiledFileName);
            sb.Append(" --summary_detail_level 1");
            sb.AppendFormat(" --compilation_level {0}", Arguments.CompileOption);
            return sb.ToString();
        } 

       
    }
}
